package com.xxcloud.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateUtils;

/**
 * @author leo
 */
public class DateTimeUtil {

    /**
     * 默认的日期格式
     */
    public static final String DEFAULT_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static final String DATE_PATTERN = "yyyy-MM-dd";

    public static final String DATE_PATTERN_NOT_SPLIT = "yyyyMMdd";

    public static final String DATE_PATTERN_YEAR = "yyyy";

    public static final String DATE_NUMBER_PATTERN = "yyyyMMddHHmmss";

    public static final String DATE_TIME_PATTERN_MM = "yyyy-MM-dd HH:mm";

    public static final String DATE_PATTERN_TALENT_BIRTHDAY = "yyyy.MM.dd";

    public static final String DATE_PATTERN_TALENT_BIRTHDAY_NEW = "yyyy.MM";

    public static final String DATE_PATTERN_HH_MM_SS = "HHmmss";

    public static final String DATE_PATTERN_YYYY_MM = "yyyy-MM";

    private static final SimpleDateFormat LONG_FORMAT = new SimpleDateFormat(DEFAULT_TIME_PATTERN);
    private static final SimpleDateFormat SHORT_FORMAT = new SimpleDateFormat(DATE_PATTERN);

    /**
     * 获取昨天的开始时间
     * 
     * @return
     */
    public static Date getYesterdayStartTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        return getStartTimeOfDay(calendar);
    }

    /**
     * 获取指定时间的季度第一天
     */

    public static Date getQuarterStart(Date date) {
        return getQuarterStart(date, 0, 0, 0);
    }

    public static Date getQuarterStart(Date date, int hour, int minutes, int seconds) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        int month = getQuarterInMonth(calendar.get(Calendar.MONTH), true);
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return getStartTimeOfQuarter(calendar, hour, minutes, seconds);
    }

    public static Date getStartTimeOfQuarter(Calendar calendar, int hour, int minutes, int seconds) {
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), hour, minutes, seconds);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取指定时间的季度最后一天
     */
    public static Date getQuarterEnd(Date date) {
        return getQuarterEnd(date, 23, 59, 58);
    }

    public static Date getQuarterEnd(Date date, int hour, int minutes, int seconds) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        int month = getQuarterInMonth(calendar.get(Calendar.MONTH), false);
        calendar.set(Calendar.MONTH, month + 1);
        calendar.set(Calendar.DAY_OF_MONTH, 0);
        return getEndTimeOfQuarter(calendar, hour, minutes, seconds);
    }

    private static Date getEndTimeOfQuarter(Calendar calendar, int hour, int minutes, int seconds) {
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), hour, minutes, seconds);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    private static int getQuarterInMonth(int month, Boolean isQuarterStart) {
        int months[] = { 0, 3, 6, 9 };
        if (!isQuarterStart) {
            months = new int[] { 2, 5, 8, 11 };
        }
        if (month >= 0 && month <= 2) {
            return months[0];
        } else if (month >= 3 && month <= 5) {
            return months[1];
        } else if (month >= 6 && month <= 8) {
            return months[2];
        } else {
            return months[3];
        }
    }

    public static Date getTodayStartTime() {
        Calendar calendar = Calendar.getInstance();
        return getStartTimeOfDay(calendar);
    }

    /**
     * 获取指定时间内昨天的开始时间
     */
    public static Date getYesterdayStartByParams(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1);
        return getStartTimeOfDay(calendar);
    }

    /**
     * 获取指定时间内昨天的结束时间
     */
    public static Date getYesterdayEndByParams(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1);
        return getEndTimeOfDay(calendar);
    }

    /**
     * 获取指定时间+1（明天）的开始时间
     */
    public static Date getTomorrowStartByParam(Date date) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, 1);
        return getStartTimeOfDay(calendar);
    }

    /**
     * 获取参数:date的开始时间
     */
    public static Date getStartTimeByParam(Date date) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return getStartTimeOfDay(calendar);
    }

    /**
     * 获取参数:date的结束时间
     */
    public static Date getEndTimeByParam(Date date) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return getEndTimeOfDay(calendar);
    }

    /**
     * 获取昨天的结束时间
     * 
     * @return
     */
    public static Date getYesterdayEndTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        return getEndTimeOfDay(calendar);
    }

    public static Date getTodayEndTime() {
        Calendar calendar = Calendar.getInstance();
        return getEndTimeOfDay(calendar);
    }

    /**
     * 获取本周的开始时间
     * 
     * @return
     */
    public static Date getThisWeekStartTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return getStartTimeOfDay(calendar);
    }

    /**
     * 获取本周的结束时间
     * 
     * @return
     */
    public static Date getThisWeekEndTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        return getEndTimeOfDay(calendar);
    }

    /**
     * 获取上周的开始时间
     * 
     * @return
     */
    public static Date getLastWeekStartTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -7);
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return getStartTimeOfDay(calendar);
    }

    /**
     * 获取上周的结束时间
     * 
     * @return
     */
    public static Date getLastWeekEndTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -7);
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        return getEndTimeOfDay(calendar);
    }

    /**
     * 获取当月的开始时间
     * 
     * @return
     */
    public static Date getThisMonthStartTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return getStartTimeOfDay(calendar);
    }

    /**
     * 获取当月的结束时间
     * 
     * @return
     */
    public static Date getThisMonthEndTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 0);
        return getEndTimeOfDay(calendar);
    }

    public static Date getMonthStartTimeByDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return getStartTimeOfDay(calendar);
    }

    /** 获得指定时间当前月的最后时间（23.59.59可能会因为1秒误差出问题，这里用23.59.58） **/
    public static Date getMonthEndTimeByDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
        return getApproachesEndTimeOfDay(calendar);
    }

    public static Date getApproachesEndTimeOfDay(Calendar calendar) {
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 23, 59, 58);
        return calendar.getTime();
    }

    /**
     * 获取上月的开始时间
     * 
     * @return
     */
    public static Date getLastMonthStartTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return getStartTimeOfDay(calendar);
    }

    /**
     * 获取上月的结束时间
     * 
     * @return
     */
    public static Date getLastMonthEndTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 0);
        return getEndTimeOfDay(calendar);
    }

    /**
     * 获取一天的开始时间
     * 
     * @return
     */
    public static Date getStartTimeOfDay(Calendar calendar) {
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取一天的结束时间
     * 
     * @return
     */
    public static Date getEndTimeOfDay(Calendar calendar) {
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 23, 59, 59);
        return calendar.getTime();
    }

    /**
     * 将一个日期增加count天
     * 
     * @param date
     * @param count
     * @return
     */
    public static Date addDate(Date date, int count) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, count);
        return cal.getTime();
    }

    /**
     * 将一个日期增加count月
     * 
     * @param date
     * @param count
     * @return
     */
    public static Date addMonth(Date date, int count) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, count);
        return cal.getTime();
    }

    /**
     * 将日期格式化成一个字符串
     * 
     * @param date
     * @param pattern
     * @return
     */
    public static String dateString(Date date, String pattern) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat dateFm = new SimpleDateFormat(pattern);
        String dateTime = dateFm.format(date);
        return dateTime;
    }

    /**
     * 功能描述: 将日期转换成默认格式字符串<br>
     */
    public static String dateString(Date date) {
        return dateString(date, DEFAULT_TIME_PATTERN);
    }

    /**
     * 功能描述: 将毫秒转换成日期<br>
     *
     * @param millis 毫秒数
     */
    public static Date convert2Date(long millis) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(millis);
        return cal.getTime();
    }

    /**
     * 计算两个日期之间相差月数 （date1- date2）
     * 
     * @param date1
     * @param date2
     * @return
     */
    public static int monthsBetween(Date date1, Date date2) {
        Calendar cal1 = new GregorianCalendar();
        cal1.setTime(date1);
        Calendar cal2 = new GregorianCalendar();
        cal2.setTime(date2);
        return (cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR)) * 12 + cal1.get(Calendar.MONTH) - cal2.get(Calendar.MONTH);
    }

    /**
     * 计算两个日期之间相差的天数
     * 
     * @param smdate 较小的时间
     * @param bdate 较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static long daysBetween(Date startDate, Date endDate) {
        Calendar startC = DateUtils.toCalendar(startDate);
        Calendar endC = DateUtils.toCalendar(endDate);
        startC.set(Calendar.HOUR_OF_DAY, 0);
        startC.set(Calendar.MINUTE, 0);
        startC.set(Calendar.SECOND, 0);
        startC.set(Calendar.MILLISECOND, 0);

        endC.set(Calendar.HOUR_OF_DAY, 0);
        endC.set(Calendar.MINUTE, 0);
        endC.set(Calendar.SECOND, 0);
        endC.set(Calendar.MILLISECOND, 0);

        return (endC.getTimeInMillis() - startC.getTimeInMillis()) / (24 * 60 * 60 * 1000);
    }

    /**
     * 计算两个日期之间相差的分钟
     * 
     * @param smdate 较小的时间
     * @param bdate 较大的时间
     * @return 相差分钟
     * @throws ParseException
     */
    public static long minutesBetween(Date smdate, Date bdate) {
        return Math.abs(bdate.getTime() - smdate.getTime()) / (1000 * 60);
    }

    public static String getHourMin(Date date) {
        if (date == null) {
            return StringUtils.EMPTY;
        }
        SimpleDateFormat df = new SimpleDateFormat("kk:mm");
        return df.format(date);
    }

    public static boolean isWeekend(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int day = cal.get(Calendar.DAY_OF_WEEK);
        if (day == Calendar.SATURDAY || day == Calendar.SUNDAY) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 
     * 功能描述: <br>
     * date间隔多少个双休日
     *
     * @param date
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static int countWeekendDays(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1);
        // TODO 可以加入判断节日方法
        boolean flag = DateTimeUtil.isWeekend(calendar.getTime());
        int count = 0;
        while (flag) {
            count++;
            calendar.add(Calendar.DATE, -1);
            // TODO 可以加入判断节日方法
            flag = DateTimeUtil.isWeekend(calendar.getTime());
        }

        return count;
    }

    /**
     * 
     * 功能描述: <br>
     * 〈获取俩个时间的年差〉
     *
     * @param beginDate
     * @param endDate
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static int yearBetween(Date beginDate, Date endDate) {
        if (beginDate == null || endDate == null) {
            return 0;
        }
        Calendar beginCalendar = Calendar.getInstance();
        beginCalendar.setTime(beginDate);

        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(endDate);

        return endCalendar.get(Calendar.YEAR) - beginCalendar.get(Calendar.YEAR);
    }

    public static int dayBetween(Date beginDate, Date endDate) {
        if (beginDate == null || endDate == null) {
            return 0;
        }
        Calendar beginCalendar = Calendar.getInstance();
        beginCalendar.setTime(beginDate);

        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(endDate);

        return endCalendar.get(Calendar.DATE) - beginCalendar.get(Calendar.DATE);
    }

    /**
     * 
     * 功能描述: <br>
     * 〈获取小时差〉
     *
     * @param minDate
     * @param maxDate
     */
    public static Long getDayDifference(Date minDate, Date maxDate) {
        Long day = (maxDate.getTime() - minDate.getTime()) / (24 * 60 * 60 * 1000);
        return day;
    }

    /**
     * 
     * 功能描述: <br>
     * 〈获取小时差〉
     *
     * @param minDate
     * @param maxDate
     */
    public static long getHourDifference(Date minDate, Date maxDate) {
        long hour = (maxDate.getTime() - minDate.getTime()) / (60 * 60 * 1000);
        return hour;
    }

    public static long getMinuteDifference(Date minDate, Date maxDate) {
        long minute = (maxDate.getTime() - minDate.getTime()) / (60 * 1000);
        return minute;
    }

    public static long getMillisecondDifference(Date minDate, Date maxDate) {
        long millisecond = maxDate.getTime() - minDate.getTime();
        return millisecond;
    }

    /**
     * 〈添加小时〉
     */
    public static Date addHour(Date date, int hour) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        ca.add(Calendar.HOUR_OF_DAY, hour);
        return ca.getTime();
    }

    public static Date addMinute(Date date, int minute) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        ca.add(Calendar.MINUTE, minute);
        return ca.getTime();
    }

    /**
     * 
     * 功能描述: <br>
     * 〈俩时间相减〉
     *
     * @param beginDate
     * @param endDate
     * @return
     * @throws ParseException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static String minusTime(Date beginDate, Date endDate) {
        if (beginDate == null || endDate == null) {
            return StringUtils.EMPTY;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long diff = beginDate.getTime() - endDate.getTime();
        String reverted = diff > 0 ? "后" : "前";
        diff = Math.abs(diff);
        if (diff < 3 * 60 * 1000) {
            return "刚刚";
        } else if (diff < 60 * 60 * 1000) {
            return (int) (Math.floor((diff) / 60 / 1000)) + "分钟" + reverted;
        } else if (diff < 24 * 60 * 60 * 1000) {
            return (int) (Math.floor((diff) / 60 / 60 / 1000)) + "小时" + reverted;
        } else if (diff < 10 * 24 * 60 * 60 * 1000L) {
            return (int) (Math.floor((diff) / 24 / 60 / 60 / 1000)) + "天" + reverted;
        } else {
            try {
                return format.format(beginDate);
            } catch (Exception e) {
                return StringUtils.EMPTY;
            }
        }
    }

    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉获取当前日期三个月前的日期
     *
     * @param date
     * @param amount 负数为指定日期之前的日期，正数为指定日期后的日期
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static Date getMonthDateBefor(Date date, int amount) {
        Calendar calendar = Calendar.getInstance(); // 得到日历
        calendar.setTime(date);// 把当前时间赋给日历
        calendar.add(Calendar.MONTH, amount); // 设置为前N月
        return calendar.getTime(); // 得到前N月的时间
    }

    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉获取指定日期N天后的日期
     *
     * @param date 指定日期
     * @param amount N天(amount 负数为指定日期之前的日期，正数为指定日期后的日期)
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static Date getDateTime(Date date, int amount) {
        Calendar calendar = Calendar.getInstance(); // 得到日历
        calendar.setTime(date);// 把当前时间赋给日历
        calendar.add(Calendar.DATE, amount); // 设置为前N天
        return calendar.getTime(); // 得到前N天的时间
    }

    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉获取两日期相隔天数
     *
     * @param date
     * @param date2
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static int getDateMinus(Date date, Date date2) {
        Calendar nowDate = Calendar.getInstance(), oldDate = Calendar.getInstance();
        nowDate.setTime(date);
        oldDate.setTime(date2);
        long timeNow = nowDate.getTimeInMillis();
        long timeOld = oldDate.getTimeInMillis();
        long days = (timeNow - timeOld) / (1000 * 60 * 60 * 24);// 化为天
        return (int) days;
    }

    /**
     * 得到几天前的时间
     * 
     * @param d
     * @param day
     * @return
     */
    public static Date getDateBefore(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        return now.getTime();
    }

    /**
     * 功能描述: 字符串转为日期【自适应格式】
     *
     * @param str
     * @return
     */
    public static Date strToDate(String dateStr) {
        if (dateStr == null) {
            return null;
        }
        String pattern = null;
        if (dateStr.length() < DEFAULT_TIME_PATTERN.length()) {
            // 兼容1985.7这种格式， .直接替换为-
            if (dateStr.contains(".")) {
                dateStr = dateStr.replace(".", "-");
            }
            if (dateStr.indexOf("-") > 0) { // 2016-12-12或2016-12-12 12:34:56等等
                String[] dateStrs = dateStr.split("-");
                if (dateStrs.length == 3) { // 2016-12-12...
                    String yyyy = dateStrs[0], mm = dateStrs[1], ddhh = dateStrs[2];
                    if (ddhh.length() < 3) {
                        pattern = ((yyyy.length() >= 4) ? "yyyy" : "yyyy".substring(0, yyyy.length())) + "-" + ((mm.length() < 2) ? "M" : "MM") + "-"
                                + ((ddhh.length() < 2) ? "d" : "dd");
                    } else {
                        String dd = ddhh.substring(0, 2).trim();
                        pattern = ((yyyy.length() >= 4) ? "yyyy" : "yyyy".substring(0, yyyy.length())) + "-" + ((mm.length() < 2) ? "M" : "MM") + "-"
                                + ((dd.length() < 2) ? "d" : "dd");
                        int idx = ddhh.indexOf(" ");
                        if (idx > 0) {
                            String hhmmss = ddhh.substring(idx + 1);
                            if (!"".equals(hhmmss)) {
                                if (hhmmss.indexOf(":") > 0) { // 12:34或12:34:56
                                    String[] dateStrsTmp = hhmmss.split(":");
                                    if (dateStrsTmp.length == 1) {
                                        String hh = dateStrsTmp[0];
                                        pattern = pattern + " " + ((hh.length() < 2) ? "H" : "HH");
                                    } else if (dateStrsTmp.length == 2) {
                                        String hh = dateStrsTmp[0], m = dateStrsTmp[1];
                                        pattern = pattern + " " + ((hh.length() < 2) ? "H" : "HH") + ":" + ((m.length() < 2) ? "m" : "mm");
                                    } else if (dateStrsTmp.length == 3) {
                                        String hh = dateStrsTmp[0], m = dateStrsTmp[1], ss = dateStrsTmp[2];
                                        pattern = pattern + " " + ((hh.length() < 2) ? "H" : "HH") + ":" + ((m.length() < 2) ? "m" : "mm") + ":"
                                                + ((ss.length() < 2) ? "s" : "ss");
                                    }
                                } else if (hhmmss.length() < 3) {
                                    pattern = pattern + " " + ((hhmmss.length() < 2) ? "H" : "HH");
                                }
                            }
                        }
                    }
                } else if (dateStrs.length == 2) { // 2015-12
                    String yyyy = dateStrs[0], mm = dateStrs[1];
                    pattern = ((yyyy.length() >= 4) ? "yyyy" : "yyyy".substring(0, yyyy.length())) + "-" + ((mm.length() < 2) ? "M" : "MM");
                }
            } else if (dateStr.indexOf(":") > 0) { // 12:34或12:34:56
                String[] dateStrs = dateStr.split(":");
                if (dateStrs.length == 1) {
                    String hh = dateStrs[0];
                    pattern = (hh.length() < 2) ? "H" : "HH";
                } else if (dateStrs.length == 2) {
                    String hh = dateStrs[0], mm = dateStrs[1];
                    pattern = ((hh.length() < 2) ? "H" : "HH") + ":" + ((mm.length() < 2) ? "m" : "mm");
                } else if (dateStrs.length == 3) {
                    String hh = dateStrs[0], mm = dateStrs[1], ss = dateStrs[2];
                    pattern = ((hh.length() < 2) ? "H" : "HH") + ":" + ((mm.length() < 2) ? "m" : "mm") + ":" + ((ss.length() < 2) ? "s" : "ss");
                }
            } else if (dateStr.matches("^[0-9]*$")) { // 20161212123456【2016-12-12 12:34:56】
                int length = dateStr.length();
                if (length == 9 | length == 10) {
                    return new Date(StringTools.getLong(dateStr, 0) * 1000);
                }
                if (length == 13) {
                    return new Date(StringTools.getLong(dateStr, 0));
                }
                if (length > 3 && length < 15) { // 从年开始
                    pattern = "yyyyMMddHHmmss".substring(0, length);
                }
            }
        } else {
            pattern = DEFAULT_TIME_PATTERN;
        }
        // System.out.print(dateStr + " ： " + pattern + " ");
        if (pattern == null || dateStr.length() < pattern.length()) {
            return null;
        }
        return dateStrToDate(dateStr, pattern);
    }

    private static Date dateStrToDate(String dateStr, String pattern) {
        if (StringUtils.isEmpty(dateStr)) {
            return null;
        }
        pattern = StringUtils.isEmpty(pattern) ? DEFAULT_TIME_PATTERN : pattern;
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date result = null;
        try {
            result = format.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    /** 根据pattern、时间字符串得到相应各式的时间 **/
    public static Date strToDate(String dateStr, String pattern) {
        if (StringUtils.isEmpty(dateStr)) {
            return null;
        }
        pattern = StringUtils.isEmpty(pattern) ? DEFAULT_TIME_PATTERN : pattern;
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date result = null;
        try {
            result = format.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    /** 根据pattern、时间字符串得到相应各式的时间 **/
    public static Date strToDateNew(String dateStr, String pattern) {
        if (StringUtils.isEmpty(dateStr)) {
            return null;
        }
        // 兼容1985.7.6 、1975.08.5、1975.8.15 1975.8这种把0省略的格式，先 把.直接替换为-，再适配
        if (dateStr.contains(".")) {
            dateStr = dateStr.replace(".", "-");
        }

        if (dateStr.indexOf("-") > 0) {
            String[] dateStrs = dateStr.split("-");
            if (dateStrs.length == 3) {
                String yyyy = dateStrs[0], mm = dateStrs[1], ddhh = dateStrs[2];
                if (ddhh.length() < 3) { // 说明只有年月日 1985.7.6 、1975.08.5、1975.8.15
                    dateStr = yyyy + "-" + ((mm.length() < 2) ? "0" + mm : mm) + "-" + ((ddhh.length() < 2) ? "0" + ddhh : ddhh) + " 00:00:00";
                }
            } else if (dateStrs.length == 2) { // 1975.8
                String yyyy = dateStrs[0], mm = dateStrs[1];
                dateStr = yyyy + "-" + ((mm.length() < 2) ? "0" + mm : mm) + "-01 00:00:00";
            }
        }
        pattern = StringUtils.isEmpty(pattern) ? DEFAULT_TIME_PATTERN : pattern;
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date result = null;
        try {
            result = format.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 功能描述: 获得当前年<br>
     *
     * @return
     */
    public static int getCurrentYear() {
        Calendar c = Calendar.getInstance();
        return c.get(Calendar.YEAR);
    }

    /**
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param date
     * @param strDateBegin 格式为：HH:mm:ss
     * @param strDateEnd 格式为：HH:mm:ss
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static boolean isInDate(Date date, String strDateBegin, String strDateEnd) {
        String nowTime = DateTimeUtil.dateString(date);
        int nowHour = NumberUtils.toInt(nowTime.substring(11, 13), 0);
        int nowMinu = NumberUtils.toInt(nowTime.substring(14, 16), 0);
        List<Integer> beginTime = StringTools.stringToIntegerList(strDateBegin, ":");
        List<Integer> endTime = StringTools.stringToIntegerList(strDateEnd, ":");
        if (beginTime.size() < 2 || endTime.size() < 2) {
            return false;
        }
        int beginHour = beginTime.get(0);
        int beginMinu = beginTime.get(1);
        int endHour = endTime.get(0);
        int endMinu = endTime.get(1);
        if ((nowHour > beginHour && nowHour < endHour)) {
            return true;
        } else if (nowHour == beginHour && nowHour == endHour && nowMinu >= beginMinu && nowMinu <= endMinu) {
            return true;
        } else if (nowHour == beginHour && beginHour < endHour && nowMinu >= beginMinu) {
            return true;
        } else if (beginHour < endHour && nowHour == endHour && nowMinu <= endMinu) {
            return true;
        }
        return false;
    }

    /**
     * /时间显示方式 //三个月以上采用YYYY-MM-DD，一天以上的，采用天制，1天内的采用小时制，1小时以下的采用分钟制
     *
     * @param date
     * @return
     */
    public static String dateFrontView(Date date) {
        if (date == null) {
            return "-";
        }
        Long dateTime = date.getTime();
        double compareValue = Math.floor((System.currentTimeMillis() - dateTime) / 1000);
        int SEC = 60, MIN = 3600, DAY = 86400;
        String view = "-";
        if (compareValue >= 0) {
            if (compareValue < 3 * 60) {
                view = "刚刚";
            } else if (compareValue < MIN) {
                view = (int) Math.floor(compareValue / SEC) + "分钟前";
            } else if (compareValue < DAY) {
                view = (int) Math.floor(compareValue / MIN) + "小时前";
            } else if (compareValue < 30 * DAY) {
                view = (int) Math.floor(compareValue / DAY) + "天前";
            } else {
                view = dateString(date, "yyyy-MM-dd");
            }
        } else {
            view = dateString(date, "yyyy-MM-dd");
        }
        return view;
    }

    public static int getWorkExperice(Integer startWorkYear) {
        if (startWorkYear == null || startWorkYear == 0) {
            return 0 + 1;
        }
        int workExperice = getNowYear() - startWorkYear;
        if (workExperice <= 0) {
            return 0 + 1;
        }
        return workExperice + 1;
    }

    /**
     * 根据开始工作年月获取工作年限
     * 
     * @param startWorkYear
     * @param startWorkMonth
     * @return
     */
    public static int getWorkExperice(Integer startWorkYear, Integer startWorkMonth) {
        if (startWorkYear == null || startWorkYear == 0) {
            return 0 + 1;
        }
        if (startWorkMonth == null) {
            startWorkMonth = 1;
        }
        Calendar c1 = Calendar.getInstance();
        int nowMonth = c1.get(Calendar.MONTH) + 1;
        int nowYear = c1.get(Calendar.YEAR);
        int workExperice = nowYear - startWorkYear;
        int workMonth = nowMonth - startWorkMonth;
        if (workMonth < -6) {
            workExperice--;
        } else if (workMonth >= 6) {
            workExperice++;
        }
        if (workExperice < 0) {
            return 0;
        }
        return workExperice;
    }

    public static int getNowYear() {
        Calendar c1 = Calendar.getInstance();
        return c1.get(Calendar.YEAR);
    }

    public static String strToDateString(String str) {
        if (StringTools.isBlank(str)) {
            return str;
        }
        // 兼容1985.7这种格式， .直接替换为-
        if (str.contains(".")) {
            str = str.replace(".", "-");
        }
        StringBuffer buffer = new StringBuffer();
        if (str.contains("-")) {
            String[] timeArray = str.split("-");
            int lenth = timeArray.length;
            for (int i = 0; i < lenth; i++) {
                buffer.append(clearStr(timeArray[i]));
                if (i != lenth - 1) {
                    buffer.append("-");
                }
            }
            return buffer.toString();
        }
        if (!(str.contains("年") | str.contains("月") | str.contains("日"))) {
            return buffer.toString();
        }
        int yearIndex = 0, monthIndex = 0, dayIndex = 0, beginIndex = 0;
        yearIndex = str.indexOf("年");
        monthIndex = str.indexOf("月");
        dayIndex = str.indexOf("日");
        if (yearIndex != -1) {
            String yearStr = clearStr(str.substring(beginIndex, yearIndex));
            if (StringTools.isNumeric(yearStr)) {
                buffer.append(yearStr);
            }
        }
        if (monthIndex != -1 && buffer.length() > 3) {
            String monthStr = clearStr(str.substring(yearIndex + 1, monthIndex));
            if (StringTools.isNumeric(monthStr)) {
                buffer.append("." + monthStr);
            }
        }
        if (dayIndex != -1 && buffer.length() > 6) {
            String dayStr = clearStr(str.substring(monthIndex + 1, dayIndex));
            if (StringTools.isNumeric(dayStr)) {
                buffer.append("." + dayStr);
            }
        }
        return buffer.toString();
    }

    /**
     * 清理特殊字符
     *
     * @param str
     * @return
     */
    public static String clearStr(String str) {
        if (StringTools.isBlank(str)) {
            return "";
        }
        String reg = "[`~!@#$%^&*()+=|{}':;', \\[\\].<>/?~！@#￥%……&*（）_——+|{}【】‘；：”“’。，、？\u4e00-\u9fa5]";
        Pattern pat = Pattern.compile(reg);
        str = pat.matcher(str).replaceAll("");
        str = str.replace(" ", "");
        return str;
    }

    /**
     * 当前季度的开始时间
     */
    public static Date getCurrentQuarterStartTime() {
        Calendar c = Calendar.getInstance();
        int currentMonth = c.get(Calendar.MONTH) + 1;
        Date now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 3) {
                c.set(Calendar.MONTH, 0);
            } else if (currentMonth >= 4 && currentMonth <= 6) {
                c.set(Calendar.MONTH, 3);
            } else if (currentMonth >= 7 && currentMonth <= 9) {
                c.set(Calendar.MONTH, 6);
            } else if (currentMonth >= 10 && currentMonth <= 12) {
                c.set(Calendar.MONTH, 9);
            }
            c.set(Calendar.DATE, 1);
            now = LONG_FORMAT.parse(SHORT_FORMAT.format(c.getTime()) + " 00:00:00");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 当前季度的结束时间
     */
    public static Date getCurrentQuarterEndTime() {
        Calendar c = Calendar.getInstance();
        int currentMonth = c.get(Calendar.MONTH) + 1;
        Date now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 3) {
                c.set(Calendar.MONTH, 2);
                c.set(Calendar.DATE, 31);
            } else if (currentMonth >= 4 && currentMonth <= 6) {
                c.set(Calendar.MONTH, 5);
                c.set(Calendar.DATE, 30);
            } else if (currentMonth >= 7 && currentMonth <= 9) {
                c.set(Calendar.MONTH, 8);
                c.set(Calendar.DATE, 30);
            } else if (currentMonth >= 10 && currentMonth <= 12) {
                c.set(Calendar.MONTH, 11);
                c.set(Calendar.DATE, 31);
            }
            now = LONG_FORMAT.parse(SHORT_FORMAT.format(c.getTime()) + " 23:59:59");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 
     * @param year
     * @param monthStr
     * @return
     */

    public static String getQuarterStrBy(String year, String monthStr) {
        int month = Integer.parseInt(monthStr);
        String quarter = "";
        if (month >= 1 && month <= 3) {
            quarter = "第一季度";
        } else if (month >= 4 && month <= 6) {
            quarter = "第二季度";
        } else if (month >= 7 && month <= 9) {
            quarter = "第三季度";
        } else if (month >= 10 && month <= 12) {
            quarter = "第四季度";
        }
        return year + "年" + quarter;
    }

    public static String getYearAndMonthStrBy(Date date) {
        String currentTimeStr = dateString(date, DATE_PATTERN);
        String year = currentTimeStr.substring(0, 4);
        String month = currentTimeStr.substring(5, 7);
        return year + month;
    }

    public static Date getYearBegin(Date date, int hour, int minute, int second) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(c.get(Calendar.YEAR), 0, 1, hour, minute, second);
        c.set(Calendar.MILLISECOND, 0);

        return c.getTime();
    }

    public static Date getYearEnd(Date date, int hour, int minute, int second) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(c.get(Calendar.YEAR), 11, 31, hour, minute, second);
        c.set(Calendar.MILLISECOND, 0);

        return c.getTime();
    }

    public static Date preQuarterBegin(Date date) {
        Date current = getQuarterStart(date, -10, 0, 0);

        return getQuarterStart(current, 0, 0, 0);
    }

    public static Date preQuarterEnd(Date date) {
        Date current = getQuarterStart(date, -10, 0, 0);
        return getQuarterEnd(current, 23, 59, 59);
    }

    public static long date2Long(Date date) {
        return date2Long(date, 0);
    }

    public static long date2Long(Date date, long def) {
        return date != null ? date.getTime() : def;
    }

    public static Date preYearBegin(Date date) {
        return getYearBegin(getYearBegin(date, -20, 0, 0), 0, 0, 0);
    }

    public static Date preYearEnd(Date date) {
        return getYearEnd(getYearBegin(date, -20, 0, 0), 23, 59, 59);
    }

    /**
     * 判断某个时间是否在一段时间段内
     * 
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean isBelongTime(Date nowTime, String beginStr, String endStr) {
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");// 设置日期格式
        Date now = null;
        Date beginTime = null;
        Date endTime = null;
        try {
            now = df.parse(df.format(nowTime));
            beginTime = df.parse(beginStr);
            endTime = df.parse(endStr);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        Boolean flag = belongCalendar(now, beginTime, endTime);
        return flag;
    }

    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {

    }

}
